package org.bulu.project.web.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bulu.project.system.model.dto.ChatMessage;
import org.bulu.project.system.model.entity.Chat;
import org.bulu.project.system.model.entity.ChatDetailed;
import org.bulu.project.system.security.SecurityUtils;
import org.bulu.project.system.service.ChatDetailedService;
import org.bulu.project.system.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * WebSocket 测试控制层
 *
 * @author Ray
 * @since 2.3.0
 */
@RestController
@RequestMapping("/websocket")
@RequiredArgsConstructor
@Slf4j
public class WebsocketController {

    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    private ChatService chatService;
    @Autowired
    private ChatDetailedService chatDetailedService;


    /**
     * Bulu的系统消息
     *
     * @param message 消息内容
     */
    @MessageMapping("/sendToAll")
    @SendTo("/topic/notice")
    public String sendToAll(String message) {
        return "服务端通知: " + message;
    }

    /**
     * 点对点发送消息
     * <p>
     * 模拟 张三 给 李四 发送消息场景
     *
     * @param principal 当前用户
     * @param username  接收消息的用户
     * @param message   消息内容
     */
    @MessageMapping("/sendToUser/{username}")
    public void sendToUser(Principal principal, @DestinationVariable String username, String message) {

        String sender = principal.getName(); // 发送人
        // 接收人
        String receiver = username; // 接收人

        //当前用户id
        Long id = SecurityUtils.getUserId();
        int userId = id.intValue();

        log.info("发送人:{}; 接收人:{}", sender, receiver);
        // 发送消息给指定用户，拼接后路径 /user/{receiver}/queue/greeting
        messagingTemplate.convertAndSendToUser(receiver, "/queue/greeting", new ChatMessage(sender, message));

        // 保存聊天记录
        Chat chat = new Chat();
        chat.setUserId(userId);
        chat.setAnotherId(userId);
        chat.setLatestTime(new java.util.Date());
        chat.setUnread(0);
        //int i = chatService.createChat(chat.getUserId(), chat.getAnotherId());

        ChatDetailed chatDetailed = new ChatDetailed();
        chatDetailed.setUserId(userId);
        chatDetailed.setContent(message);
        //chatDetailedService.insert(chatDetailed);
    }


/*    *//**
     * 群聊
     *//*
    @MessageMapping("/sendToAll")
    @SendTo("/topic/notice")
    public String sendToGroup(String message) {
        return "服务端通知: " + message;
    }*/


    /**
     * 消息自动推送，具体实现在Consumer中，各自实现各自的消息推送
     */


}
